package sto.orz.rptp.service;

import java.util.List;

import ognl.Ognl;
import ognl.OgnlException;

import org.apache.commons.lang.StringUtils;

import sto.orz.dao.HibernateGenericDao;
import sto.orz.html.ElementType;
import sto.orz.html.form.FormElement;
import sto.orz.html.form.Form;
import sto.orz.rptp.model.Dataset;

import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.util.OgnlValueStack;
public class FormManager {
	private HibernateGenericDao dao;
	
	public void testCRUD() {
		Object ds;
		try {
			ds = dao.findUniqueBy(Class
					.forName("sto.orz.rptp.model.Datasource"), "id",
					"1128807c0f557272010f55c8738f0002");
			String value;
			try {
				value = Ognl.getValue("id", ds).toString();
//				assertEquals("1128807c0f557272010f55c8738f0002", value);
				
				Dataset das = new Dataset();
				Ognl.setValue("datasource", das, ds);
//				assertNotNull(das.getDatasource());
			} catch (OgnlException e) {
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	public Object saveByID(String id, Object object) {
//		OgnlValueStack ognlValueStack = ActionContext.getContext().getValueStack();
//		Object dsid = ognlValueStack.findValue("dataset.datasource.id");
//		Object id = ognlValueStack.findValue("dataset.id");
//		System.out.println("");
		return null;
	}

	public Object pickupData(Form form, Object object) {
		OgnlValueStack ognlValueStack = ActionContext.getContext().getValueStack();
		Object dsid = ognlValueStack.findValue("dataset.datasource.id");
		Object id = ognlValueStack.findValue("dataset.id");
		System.out.println("");
		return null;
	}

	public Form injectData(Form form, Object object) {
		Integer dotOffset = form.getName().length() + 1;
		for (FormElement element : form.getElements()) {
			String expression = element.getName().substring(dotOffset);
			if (element.getType() == ElementType.SELECTBOX.toString()) {
				String hql = element.getValue();
				List data = dao.find(hql);
				//form.getValues().put(element.getId(), data);
				// log
				System.out.println(element.getValue());
			}
			try {
				String value = Ognl.getValue(expression, object).toString();
				if (!StringUtils.isBlank(value))
					element.setValue(value);
			} catch (Exception e) {
				//e.printStackTrace();
			}
		}

		return form;

	}

	public void setGenericDao(HibernateGenericDao dao) {
		this.dao = dao;
	}
}
